/**
 * $Id: PreferenceUitl.java,v 1.1 2011/05/20 07:28:07 jian.hu Exp $
 */
package com.example.venadaoa.tool;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.google.gson.Gson;


/**
 * 首选项工具类
 */
public class PreferenceUitl {

	// 首选项
	public static final String PREFERENCE_NAME = "PREFERENCE_VENADA"; // 首选项名称




	private static PreferenceUitl preferenceUitl;

	private SharedPreferences sp;

	private Editor ed;

	public PreferenceUitl(Context context) {
		init(context);
	}

	public void init(Context context) {
		if (sp == null || ed == null) {
			try {
				sp = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
				ed = sp.edit();
			} catch (Exception e) {
			}
		}
	}

	public static PreferenceUitl getInstance(Context context) {
		if (preferenceUitl == null) {
			preferenceUitl = new PreferenceUitl(context);
		}
		preferenceUitl.init(context);
		return preferenceUitl;
	}

	public void saveLong(String key, long l) {
		ed.putLong(key, l);
		ed.commit();
	}

	public long getLong(String key, long defaultlong) {
		return sp.getLong(key, defaultlong);
	}

	public void saveBoolean(String key, boolean value) {
		ed.putBoolean(key, value);
		ed.commit();
	}

	public boolean getBoolean(String key, boolean defaultboolean) {
		return sp.getBoolean(key, defaultboolean);
	}

	public void saveInt(String key, int value) {
		if (ed != null) {
			ed.putInt(key, value);
			ed.commit();
		}
	}

	public int getInt(String key, int defaultInt) {
		return sp.getInt(key, defaultInt);
	}

	public String getString(String key, String defaultInt) {
		return sp.getString(key, defaultInt);
	}

	public boolean containKey(String key){
		boolean is = sp.contains(key);
		return is;
	}

	public String getString(Context context, String key, String defaultValue) {
		if (sp == null || ed == null) {
			sp = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_MULTI_PROCESS);
			ed = sp.edit();
		}
		if (sp != null) {
			return sp.getString(key, defaultValue);
		}
		return defaultValue;
	}

	public void saveString(String key, String value) {
		ed.putString(key, value);
		ed.commit();
	}



	public void remove(String key) {
		ed.remove(key);
		ed.commit();
	}

	public void destroy() {
		sp = null;
		ed = null;
		preferenceUitl = null;
	}


	/**
	 *
	 * @param key
	 * @param cls
	 *            这里传入一个类就是我们所需要的实体类(obj)
	 * @return 返回我们封装好的该实体类(obj)
	 */
	public  <T> T getBeanByGson(String key,
										  Class<T> cls) {
		String objString = sp.getString(key, "");
		return new Gson().fromJson(objString,cls);
	}


}
